package com.project.frba.bi.transformation;

import java.util.HashMap;
import java.util.Map;

import com.project.frba.bi.descriptor.Descriptor;
import com.project.frba.bi.descriptor.Dimension;
import com.project.frba.bi.extraction.ExtractionResult;

public class FactTable implements Table {

	private Descriptor descriptor;
	private Long index = 1L;
	private Map<Long, Row> factTableRows = new HashMap<Long, Row>();

	public FactTable(Descriptor descriptor) {
		this.descriptor = descriptor;
	}
	
	public FactTableRow getFactTableRowById(Long id){
		return (FactTableRow)factTableRows.get(id);
	}
	
	public Descriptor getDescriptor(){
		return descriptor;
	}
	
	private void incrementIndex(){
		this.index++;
	}
	
	public Long getActualIndex(){
		return index;
	}

	public void addRow(Row factTableRow) {
		this.factTableRows.put(this.getActualIndex(), factTableRow);
		factTableRow.setId(this.getActualIndex());
		this.incrementIndex();		
	}

	public Long process(ExtractionResult result) {
		FactTableRow factTableRow = new FactTableRow(this);
		factTableRow.setMetric(result.getMetric());
		this.addRow(factTableRow);
		return factTableRow.getId();
	}
	
	public void addField(Long factTableRowId, String dimensionName, Long value){
		FactTableRow factTableRow = this.getFactTableRowById(factTableRowId);
		factTableRow.addField(dimensionName, value);
	}
	
	public String getInsertStatement(Long startIndex, Long endIndex){
		StringBuffer insertStatement = new StringBuffer();
		insertStatement.append("INSERT INTO " + descriptor.getDescriptorName()+ "facttable_" + this.descriptor.getFacttable());
		insertStatement.append("(");
		insertStatement.append("id,");
		insertStatement.append("metric");
		for(Dimension dimension : this.descriptor.getDimensions()){
			insertStatement.append("," + dimension.getName() + "dimension");	
		}
		insertStatement.append(") VALUES ");
		
		
		for (long i = startIndex; i <= endIndex || i == getRowsLength(); i++) {
			Row row = this.factTableRows.get(i);
			insertStatement.append(row.getInsertValueStatement() + ",");			
		}
	
		return insertStatement.substring(0, insertStatement.lastIndexOf(",")) + ";";	
	}
	
	public Integer getRowsLength(){
		return this.factTableRows.size();
	}
	
}
